<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\user\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\user\model\Continent as ContinentModel;
use app\user\model\Airport as AirportModel;

/**
 * 国家控制器
 * @package app\user\admin
 */
class Country extends Admin
{
    /**
     * 邮件发送记录日志列表
     * @author 李洪波 <361951119@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $data_list = ContinentModel::where($this->getMap())->where(['type'=>'country'])
            ->order($this->getOrder('id DESC'))
            ->paginate();
        if($data_list->items()){
            foreach ($data_list->items() as &$val){
                $continent=ContinentModel::where(['id'=>$val['parent_id'],'type'=>'continent'])->value('name');
                $val['continent']=$continent;
                $val['airport']=AirportModel::where(['country'=>$val['id']])->count();
            }
        }
        $btn_access = [
            'title' => 'Import',
            'icon'  => 'fa fa-fw fa-upload',
            'class' => 'btn btn-primary ajax-post confirm',
            'href'  => url('import')
        ];

        $down_access = [
            'title' => 'Download',
            'icon'  => 'fa fa-fw fa-download',
            'class' => 'btn btn-primary',
            'href'  => PUBLIC_PATH. 'static/admin/download/countries.xls',
            'target'=>'_blank'
        ];

        $continents=ContinentModel::where(['type'=>'continent'])->column(['id','name']);
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->setTableName('area')
            ->addTopButton('add',['title'=>'Add'])
            ->addTopButton('custom', $btn_access, ['area' => ['800px', '60%'], 'title' => ['Import', 'font-size:18px;']])
            ->addTopButton('custom',$down_access)
            ->addRightButton('edit',['title'=>'edit'])
            ->addRightButton('delete',['title'=>'delete','data-title' => 'This data is associated with __airport__ Airports. Cancel the association before deleting it','data-confirm'=>'confirm','data-cancel'=>'cancel'])
            ->addColumns([
                ['id', 'ID'],
                ['name', 'Country'],
                ['abbreviation', 'Abbreviation'],
                ['phone_code', 'CC'],
                ['timezone', 'Timezone'],
//                ['flag', 'Flag','picture'],
                ['continent', 'Continent'],
                ['airport', 'Airport'],
                ['hot', 'Hot','yesno',['No','Yes']],
                ['updater', 'Updater'],
                ['update_time', 'Last update time'],
                ['right_button', 'Operation', 'btn'],
            ])
            ->setRowList($data_list)
            ->setColumnWidth([
                'abbreviation'  => 120,
                'airport'=>70,
//                'flag'  => 80,
                'phone_code'  => 50,
                'update_time'  => 150,
                'hot'  => 50,
                'updater'=>70,
                'right_button'=>70,
                'id'=>50])
            ->setSearchArea([
                ['text', 'name', 'Country','like'],
                ['select', 'parent_id', 'Continent', '', '', $continents]
            ])
            ->fetch();
    }


    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['name'] == '' && $this->error('Please fill in the Country name');
            $data['abbreviation'] == '' && $this->error('Please fill in the abbreviation');
            if(strlen($data['abbreviation'])!=3) $this->error('Abbreviation format error');

            $data['phone_code'] == '' && $this->error('Please fill in the CC');
            $data['parent_id'] == '' && $this->error('Please fill in the Continent');
            if(!$this->check($data['name'])) $this->error('Data duplicated, please re-enter');
            $list = [];
            $list['name']=$data['name'];
            $list['type']='country';
            $list['parent_id']=$data['parent_id'];
            $list['abbreviation']=strtoupper($data['abbreviation']);
            $list['phone_code']=$data['phone_code'];
            $list['hot']=$data['hot'];
//            $list['flag']=$data['flag'];
            $list['timezone']=$data['timezone'];
            $list['update_time']=date('Y-m-d H:i:s');
            $list['create_time']=date('Y-m-d H:i:s');
            $list['updater']=session('user_auth')['username'];
            $continentModel = new ContinentModel();
            if (false !== $continentModel->save($list)) {
                $this->success('add success', 'index');
            } else {
                $this->error('add failed');
            }
        }
        $continents=ContinentModel::where(['type'=>'continent'])->column(['id','name']);
        return ZBuilder::make('form')
            ->addFormItems([
                ['text', 'name', 'Country'],
                ['text', 'abbreviation', 'Abbreviation'],
                ['text', 'phone_code', 'CC'],
                ['select','parent_id','Continent','',$continents],
                ['number','timezone','Timezone','','',-24,24],
                ['radio','hot','Hot','',[0=>'No',1=>'Yes'],0],
//                ['image','flag', 'Flag'],

            ])
            ->fetch();
    }


    public function edit($id = 0)
    {
        if ($id === 0) $this->error('missing parameter');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');
            // 验证
            $data['name'] == '' && $this->error('Please fill in the Country name');
            $data['abbreviation'] == '' && $this->error('Please fill in the abbreviation');
            if(strlen($data['abbreviation'])!=3) $this->error('Abbreviation format error');
            $data['phone_code'] == '' && $this->error('Please fill in the CC');
            $data['parent_id'] == '' && $this->error('Please fill in the Continent');
            if(!$this->check($data['name'],$id)) $this->error('Data duplicated, please re-enter');
            $data['abbreviation']=strtoupper($data['abbreviation']);
            $data['update_time']=date('Y-m-d H:i:s');
            $data['updater']=session('user_auth')['username'];
            if (ContinentModel::update($data,['id'=>$id])) {
                $this->success('edit success', 'index');
            } else {
                $this->error('edit failed');
            }
        }
        // 获取数据
        $info = ContinentModel::get($id);
        $continents=ContinentModel::where(['type'=>'continent'])->column(['id','name']);
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->addFormItems([
                ['text', 'name', 'Country'],
                ['text', 'abbreviation', 'Abbreviation'],
                ['text', 'phone_code', 'CC'],
                ['select','parent_id','Continent','',$continents],
                ['number','timezone','Timezone','','',-24,24],
                ['radio','hot','Hot','',[0=>'No',1=>'Yes'],0],
//                ['image','flag', 'Flag'],
            ])
            ->setFormData($info)
            ->fetch();
    }

    private function check($name,$id=0){
        $id=ContinentModel::where(['name'=>$name])
            ->when($id,function ($query)use($id){
                $query->where('id','neq',$id);
            })
            ->value('id');
        if($id){
            return false;
        }else{
            return true;
        }
    }

    public function delete($record = []){
        $ids   = $this->request->isPost() ? input('post.ids/a') : input('param.ids');

        //判断是否存在关联飞机场
        $airport=ContinentModel::where(['id'=>$ids])->value('airport');
        if($airport) $this->error('Please remove the associated airport first, and then delete');
        //判断是否有下属城市
        $country=ContinentModel::where(['parent_id'=>$ids,'type'=>'city'])->count();
        if($country) $this->error('Please remove the associated city first, and then delete');

        ContinentModel::where(['id'=>$ids])->delete();
        $this->success('delete success','index');
    }

    public function import(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $file_path=get_file_path($data['file']);
            if(empty($data['file'])) $this->error('please upload excel file!');
//            $ext = pathinfo($file_path);
//            //设置excel格式
//            $type = strtolower($ext["extension"]);
//            if($type=='xlsx'){
//                $type='Excel2007';
//            }elseif ($type=='csv'){
//                $type='csv';
//            }else{
//                $type='Excel5';
//            }
            require_once($_SERVER['DOCUMENT_ROOT'].'/../extend/PHPExcel/PHPExcel/IOFactory.php');
            $objPHPExcel = \PHPExcel_IOFactory::load($_SERVER['DOCUMENT_ROOT'].$file_path);
            //默认选中sheet0表
            $sheetSelected = 0;
            $objPHPExcel->setActiveSheetIndex($sheetSelected);
            //获取表格行数
            $rowCount = $objPHPExcel->getActiveSheet()->getHighestRow();
            //获取表格列数
            $columnCount = $objPHPExcel->getActiveSheet()->getHighestColumn();
            $list=[];
            for ($row = 2; $row <= $rowCount; $row++) {
                $dataArr = array();
                for ($column = 'A'; $column <= $columnCount; $column++) {
                    $dataArr['name']=trim($objPHPExcel->getActiveSheet()->getCell('A' . $row)->getValue());
                    $dataArr['abbreviation']=strtoupper($objPHPExcel->getActiveSheet()->getCell('B' . $row)->getValue());
                    $dataArr['phone_code']=$objPHPExcel->getActiveSheet()->getCell('C' . $row)->getValue();
                    $dataArr['parent_name']=$objPHPExcel->getActiveSheet()->getCell('D' . $row)->getValue();
                    $dataArr['hot']=intval($objPHPExcel->getActiveSheet()->getCell('E' . $row)->getValue());
                    $dataArr['timezone']=intval($objPHPExcel->getActiveSheet()->getCell('F' . $row)->getValue());
                }
                $list[]=$dataArr;
            }
            if($list){
                $continentModel=new ContinentModel();
                $rep=$continentModel->addAll($list,'continent',session('user_auth')['username']);
                if($rep['code']==1){
                    $this->success('excel file import success','index', '_parent_reload');
                }else{
                    $this->error($rep['msg']);
                }
            }else{
                $this->error('excel file data is empty!');
            }

        }

        return ZBuilder::make('form')
            ->addFile('file', 'Country File', '', '', '','xlsx,csv,xls')
            ->fetch();
    }
}
